import { Component, OnInit } from '@angular/core';
import { Rpower } from '../../../entity/rpower.model';
import { ApplicationService } from 'app/service/application.service';
import { LossElectricityService, PowerType } from 'app/service/loss-electricity.service';
import { Farm } from 'app/entity/farm.model';
import { DatePipe } from '@angular/common';
import { TreeNode, ConfirmationService } from 'primeng/primeng';
// 表格导出为Excel
import * as XLSX from 'xlsx';

@Component({
  selector: 'app-r-power',
  templateUrl: './r-power.component.html',
  styleUrls: ['./r-power.component.css']
})
export class RPowerComponent implements OnInit {
  startTime = new Date(new Date().getTime() - 1000 * 60 * 60 * 24);
  endTime = new Date(new Date().getTime() - 1000 * 60 * 60 * 24);
  years: string[] = [];
  months: string[] = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  startYear: string = this.startTime.getFullYear().toString();
  startMonth: string = this.months[this.startTime.getMonth()].toString();
  endYear: string = this.startTime.getFullYear().toString();
  endMonth: string = this.months[this.startTime.getMonth()].toString();
  active = 0;
  rPowers: Rpower[] = [];
  /* rPower: Rpower; */
  /* selectedRPower: Rpower; */
  fileOther: File;
  file: File;
  fileSpeed: File;
  farms: Farm[] = [];
  selectFarmId: number;
  powerTypes = [];
  selectOptions: PowerType[] = [];
  selectedOption: number;
  powerCategorytag: number;
  en = {
    firstDayOfWeek: 0,
    dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
    dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
    today: '今天',
    clear: '清除'
  };
  private fomat: string = 'yyyy-MM-dd';
  /* displayDialog = false;
  changeValue = 0;
  currentRpower: Rpower; */
  rPowerMonths: Rpower[] = [];
  rPowerYears: Rpower[] = [];
  constructor(
    public application: ApplicationService,
    private lossElectricity: LossElectricityService,
    private datePipe: DatePipe,
    private confirmation: ConfirmationService,

  ) { }

  ngOnInit() {
    let year = new Date().getFullYear();
    this.years.push(year.toString());
    for (let i = 0; i <= 10; i++) {
      year--;
      this.years.push(year.toString());
    }
    this.lossElectricity.getPowerType()
      .then(res => {
        if (res) {
          const index = res.findIndex(o => o.categoryKey === 'Power');
          if (index >= 0) {
            this.selectedOption = res[index].categorytag;
            this.powerCategorytag = res[index].categorytag;
          }
          this.selectOptions = [...res];
          this.onSearch();
        }
      });

    this.farms = this.application.currentUserFarms;
  }
  onClick(active: number) {
    this.active = active;
    this.rPowers = [];
  }
  /* onRowSelect(event) {
    this.selectFarmId = this.selectedRPower.farmId;
    this.currentRpower = event.data;
    this.changeValue = event.data.value;
    this.displayDialog = true;
  } */
  onSearch() {
    let startTime = '',
      endTime = '',
      dateType = 1;
    // const dateFomat = this.datePipe.transform(time, this.fomat);
    if (this.active === 0) {
      dateType = 1;
      if (this.startTime.getTime() > this.endTime.getTime()) {
        alert('开始时间不能大于结束时间');
        return false;
      }
      startTime = this.datePipe.transform(this.startTime, this.fomat);
      endTime = this.datePipe.transform(this.endTime, this.fomat);
    } else if (this.active === 1) {
      dateType = 2;
      startTime = `${this.startYear}-${this.startMonth}`;
      endTime = `${this.endYear}-${this.endMonth}`;
    } else if (this.active === 2) {
      dateType = 3;
      if (this.startYear > this.endYear) {
        alert('开始时间不能大于结束时间');
        return false;
      }
      startTime = `${this.startYear}-01-01`;
      endTime = `${this.endYear}-12-31`;
    }
    this.lossElectricity.getFarmPowerByTime(startTime, endTime, dateType, [this.selectedOption])
      .then(res => {
        if (res) {
          if (dateType == 1) {
            const result = [];
            const rPowers = res.filter(rpower => rpower.dateType == 1 && !rpower.phaseId);
            const rPowerPhases = res.filter(rpower => rpower.dateType == 1 && rpower.phaseId);
            const rPowersMonth = res.filter(rpower => rpower.dateType == 2);
            const rPowersYear = res.filter(rpower => rpower.dateType == 3);
            rPowers.forEach(rpower => {
              // tslint:disable-next-line:max-line-length
              let index = rPowersMonth.findIndex(rPowerMonth => rPowerMonth.farmId == rpower.farmId && rPowerMonth.date == rpower.date && !rPowerMonth.phaseId);
              if (index >= 0) {
                rpower.valueMonth = rPowersMonth[index].value;
              } else {
                rpower.valueMonth = 0;
              }
              // tslint:disable-next-line:max-line-length
              index = rPowersYear.findIndex(rPowerYear => rPowerYear.farmId == rpower.farmId && rPowerYear.date == rpower.date && !rPowerYear.phaseId);
              if (index >= 0) {
                rpower.valueYear = rPowersYear[index].value;
              } else {
                rpower.valueYear = 0;
              }
              result.push(rpower);
              const filterPhases = rPowerPhases.filter(o => o.farmId === rpower.farmId && o.date == rpower.date);
              filterPhases.forEach(phaseRpower => {
                // tslint:disable-next-line:max-line-length
                index = rPowersMonth.findIndex(rPowerMonth => rPowerMonth.farmId == phaseRpower.farmId && rPowerMonth.date == phaseRpower.date && rPowerMonth.phaseId === phaseRpower.phaseId);
                if (index >= 0) {
                  phaseRpower.valueMonth = rPowersMonth[index].value;
                } else {
                  phaseRpower.valueMonth = 0;
                }
                // tslint:disable-next-line:max-line-length
                index = rPowersYear.findIndex(rPowerYear => rPowerYear.farmId == phaseRpower.farmId && rPowerYear.date == phaseRpower.date && rPowerYear.phaseId === phaseRpower.phaseId);
                if (index >= 0) {
                  phaseRpower.valueYear = rPowersYear[index].value;
                } else {
                  phaseRpower.valueYear = 0;
                }
                result.push(phaseRpower);
              });
            });
            this.rPowers = [...result];
          } else if (dateType == 2) {
            const result = [];
            const rPowerMonths = [...res.filter(o => !o.phaseId)];
            const rPowerMonthsPhase = [...res.filter(o => o.phaseId)];
            rPowerMonths.forEach(rPower => {
              result.push(rPower);
              const filterPhases = rPowerMonthsPhase.filter(o => o.farmId === rPower.farmId && rPower.date == o.date);
              filterPhases.forEach(o => {
                result.push(o);
              });
            });
            this.rPowerMonths = [...result];
          }
          else if (dateType == 3) {
            const result = [];
            const rPowerYears = [...res.filter(o => !o.phaseId)];
            const rPowerYearsPhase = [...res.filter(o => o.phaseId)];
            rPowerYears.forEach(rPower => {
              result.push(rPower);
              const filterPhases = rPowerYearsPhase.filter(o => o.farmId === rPower.farmId && rPower.date == o.date);
              filterPhases.forEach(o => {
                result.push(o);
              });
            });
            this.rPowerYears = [...result];
          }

        }
      })
      .catch(err => {
        console.log(err);
      });
  }
  onImport() {
    this.lossElectricity.importBattery(this.file)
      .then(res => {
        if (res && res.code == '200') {
          alert('导入成功！');
          this.onSearch();
          this.onRemoveOther();
        } else {
          alert('导入失败');
        }
      })
      .catch(err => {
        alert('导入失败');
      });
  }

  onUpload(ev) {
    this.file = ev.files;
    this.onImport();

  }
  onRemove() {
    this.file = null;
  }
  onUploadOther(ev) {
    this.fileOther = ev.files;
    this.lossElectricity.importOtherBattery(this.fileOther)
      .then(res => {
        if (res && res.code == '200') {
          alert('导入成功！');
          this.onSearch();
          this.onRemoveOther();
        } else {
          alert('导入失败');
        }
      }).catch(err => {
        alert('导入失败');
      });

  }
  onRemoveOther() {
    this.fileOther = null;
  }
  onUploadSpeed(ev) {
    this.fileSpeed = ev.files;
    this.lossElectricity.importAvgwindspeed(this.fileSpeed)
      .then(res => {
        if (res && res.code == '200') {
          alert('导入成功！');
          this.onRemoveSpeed();
        } else {
          alert('导入失败');
        }
      }).catch(err => {
        alert('导入失败');
      });

  }
  onRemoveSpeed() {
    this.fileSpeed = null;
  }
  export(active, id, title) {
    let str = '';
    const fomat = 'yyyy.MM.dd';
    if (active) {
      str = ` 
    <thead >
      <tr>
      <th>${title}</th>
      </tr>
    </thead>
    <thead>
      <tr>
        <th>风场</th>
        <th>工期</th>
        <th>值(kwh)</th>
        <th>电量类型</th>
        <th>时间</th>
        <th>时间类型</th>
      </tr>
    </thead>
    <tbody>`;
      this.rPowers.forEach(rpower => {
        let plantType = '';
        let date = '';
        if (rpower.dateType == 1) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '日';
        } else if (rpower.dateType == 2) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '月';
        }
        else if (rpower.dateType == 3) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '年';
        }
        str += `<tr >
        <td>${rpower.farmName}</td>
        <td>${rpower.phaseName}</td>
        <td>${rpower.value}</td>
        <td>${rpower.powerName}</td>
        <td>${date}</td>
        <td>${plantType}</td>
        
      </tr>`;
      });
    } else {
      str = `
    <thead >
      <tr>
      <th>${title}</th>
      </tr>
    </thead>
    <thead>
      <tr>
      <th>风场</th>
      <th>工期</th>
      <th>风机</th>
      <th>值(kwh)</th>
      <th>时间</th>
      <th>时间类型</th>
      </tr>
    </thead>
    <tbody>`;
      this.rPowers.forEach(rpower => {
        let plantType = '';
        let date = '';
        if (rpower.dateType == 1) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '日';
        } else if (rpower.dateType == 2) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '月';
        }
        else if (rpower.dateType == 3) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '年';
        }
        str += `<tr >
      <td>${rpower.farmName}</td>
      <td>${rpower.phaseName}</td>
      <td>${rpower.deviceName ? rpower.deviceName : ''}</td>
      <td>${rpower.value}</td>
      <td>${date}</td>
      <td>${plantType}</td>
      
    </tr>`;
      });
    }
    /* start = this.datePipe.transform(this.startTime, fomat),
    end = this.datePipe.transform(this.endTime, fomat); */

    str += `</tbody>`;
    const elemTable = document.createElement('table');
    elemTable.innerHTML = str;
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    var ws = XLSX.utils.table_to_sheet(elemTable);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    /* save to file */
    XLSX.writeFile(wb, title + '.xlsx');
  }
  exportData(active, id) {
    let title = '发电量';
    if (active) {
      title = '其他电量'
    }
    this.confirmation.confirm({
      header: "提示信息",
      message: `是否导出${title}电量?`,
      accept: () => {
        this.export(active, id, title);
      },
      reject: () => {

      }

    });

  }
  /* save() {
    const rpower = new Rpower(0, 0, 0, 0, 0, new Date());
    // tslint:disable-next-line:forin
    for (let prop in this.currentRpower) {
      rpower[prop] = this.currentRpower[prop];
    }
    rpower.value = this.changeValue;
    this.lossElectricity.update(rpower)
      .then(res => {
        this.displayDialog = false;
        this.onSearch();
        console.log("updata");
      });
  } */
}
interface SelectOption {
  label: string;
  value: string;
  code?: string;
  keyValue?: string;
}



// WEBPACK FOOTER //
// ./src/app/module/data-analysis/r-power/r-power.component.ts